<?
if ($zdir == 1) { $pre = '../'; }

// REQUIRED & INCLUDE FILES
require($pre."includes/date_parse.php");
require($pre."includes/date_conversion.php");
require($pre."includes/config.inc.php");
//require($pre."includes/functionsAJAX.php");

// Check for page requiring logged in user
session_start();
if ($loggedUser == 1) {
	if (!empty($member)) { $reDir = "login.php?member=1"; }
	else { $reDir = "login.php"; }
	if (empty($_SESSION['logged'])) { header("Location: $reDir"); }
}

$pathInfo = pathinfo($PHP_SELF);

function fieldToDB($string,$urlClick=null) {
	// Trim whitespace
		$string = trim($string);
	// Check for HTML characters
		$string = str_replace(Chr(10), '{lb}', $string);
		$string = str_replace('\r\n', '{lb}', $string);
		$string = htmlspecialchars($string,ENT_QUOTES,"UTF-8");
	// Make URL's clickable if required
		if ($urlClick == 1) {
			$string = parseURLS($string,false,'_blank');	
		}	
	
	// Prevent SQL injection
		$string = mysql_real_escape_string($string);	
	// Insert line breaks if needed
		$string = str_replace('{lb}', '<br>', $string);
	
	return $string;
}
function DBToField($string) {
	$string = htmlspecialchars_decode($string,ENT_QUOTES);
	$string = str_replace('&quot;', '"', $string);
	// Insert line breaks
	$string = str_replace('<br>', chr(10), $string);
	$string = str_replace('<br>', '\n', $string);
	// Replace HTML entities characters with HTML
	$string = stripslashes($string);
	return $string;
}
function DBToEmail($string) {
	$string = html_entity_decode($string);
	// Insert line breaks
	$string = str_replace('<br>', Chr(10), $string);
	$string = str_replace('<br />', Chr(10), $string);
	// Get rid of any HTML tags
	$string = strip_tags($string);
	$string = stripslashes($string);
	return $string;
}

function cleanString($fn) {
	global $cleanString;
		
	$fn = stripslashes($fn);	
	$patArray  = array('&#039;','&amp;','#','$',' ',Chr(39),Chr(35),Chr(38),'!','?','*','(',')',':',';','+','=',',');
	$replArray = array('','','','','-','','','','','','','','','','','','','');
	
	$pats = count($patArray);
	
	for($a=0;$a<=($pats-1);$a++) {
		$fn = (str_replace($patArray[$a], $replArray[$a], $fn));
	} 
		
	$cleanString = $fn;
	return $cleanString;
}

// Determine Browser
$browser = strstr(getenv('HTTP_USER_AGENT'), 'MSIE');
if (!empty($browser)) {
	// Check for Opera browser
	$opera = strstr(getenv('HTTP_USER_AGENT'), 'Opera');
	if (!empty($opera)) {
		$browser = "NS"; 
		$stylesheet = "layoutns.css";
		$jpeg_mime_type = "image/jpeg";
	} else {
		$browser = "IE"; 
		$stylesheet = "layoutie.css";
		$jpeg_mime_type = "image/pjpeg";
	}	
} else {
	$browser = "NS"; 
	$stylesheet = "layoutns.css";
	$jpeg_mime_type = "image/jpeg";
}

// Check Page --------------------------------------------- //
$selfArray = explode("/", $_SERVER[PHP_SELF]);
$elements = count($selfArray);
$last_element = $elements - 1;
$file = $selfArray[$last_element];

// Better mail function
function mailNew($fromName, $fromAddress, $to, $subject, $message) {
   // Copyright ? 2005 ECRIA LLC, http://www.ECRIA.com
   // Please use or modify for any purpose but leave this notice unchanged.
   $headers  = "MIME-Version: 1.0\n";
   $headers .= "Content-type: text/plain; charset=iso-8859-1\n";
   $headers .= "X-Priority: 3\n";
   $headers .= "X-MSMail-Priority: Normal\n";
   $headers .= "X-Mailer: php\n";
   $headers .= "From: \"".$fromName."\" <".$fromAddress.">\n";
   return mail($to,$subject,$message,$headers);
}

// Function to prevent email form injection attacks
function emailPreventInjection($input) {
	$repl = '';
	$input = (ereg_replace("\r", $repl, $input));
	$input = (ereg_replace("\n", $repl, $input));
	$input = (ereg_replace("%0a", $repl, $input));
	$input = (ereg_replace("%0d", $repl, $input));
	$input = (ereg_replace("Content-Type:", $repl, $input));
	$input = (ereg_replace("bcc:", $repl, $input));
	$input = (ereg_replace("to:", $repl, $input));
	$input = (ereg_replace("cc:", $repl, $input));
	return $input;
} 

function random_string($length) {
	global $string;
	// Generate Random Password
	mt_srand ((double) microtime() * 1000000);
	$possible = "ABCDEFGHJKLMNPQRSTUVWXYZ";
	$string = "";
	
	while (strlen($string) < $length) {
		$no_add = 0;
		$str = substr($possible, mt_rand(0, strlen($possible) - 1), 1);
		// Check that preceeding character in $password is not same as current character
				
		if (strlen($string) >= 1) {
			for ($a=1;$a<=strlen($string);$a++) {
				// $str will be current character
				if ($str == substr("$string", -$a, 1)) { $no_add = 1; }
			} // End For Loop
		} // End If
		
		if ($no_add == 1) { continue; }
		$string .= $str; // Build the password string
	} // End While loop
	return $string;
}
// Function Resize_image()
// This function accepts a jpeg image, resizes it according to a scaling factor
// and then copies it to a new file with a specified filename "extension"
// Ex. resize_image(image.jpg, 100, thumb) 
// This would generate a new JPEG file called thumb_image.jpg at 100 pixels wide

function resize_image($orig_file,$max_width,$max_height,$file_ext,$dir,$border,$mime) {
	// Determine filenames
	$fileArray = explode("/", $orig_file);
	$file_elements = count($fileArray);
	$last_element = $file_elements - 1;
	if (!empty($file_ext)) {
		$out_file = $file_ext."_".$fileArray[$last_element];
	} else {
		$out_file = $fileArray[$last_element];
	}	
	
	// Rebuild directory string for thumbnail file
	$directory = "";
	for ($a=0;$a<=($last_element - 1);$a++) {
		if (empty($directory)) {
			$directory = $fileArray[$a];
		} else {
			$directory = $directory."/".$fileArray[$a];
		}		
	}
	if (!empty($dir)) { $directory = $directory."/".$dir; }
	
	$out_file = $directory."/".$out_file;	
		
	$size = getimagesize($orig_file);
	if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
		$im_in = imagecreatefromjpeg($orig_file);
	} elseif ($mime == "image/gif") {
		$im_in = imagecreatefromgif($orig_file);
	} elseif ($mime == "image/png") {
		$im_in = imagecreatefrompng($orig_file);
	}
	
	// Get original image dimentions
	$origW = $size[0];
	$origH = $size[1];
	
	// Get scale %age - we have 3 cases here
	if (!empty($max_width) && !empty($max_height)) {
		// This is gonna be tricky 'cause we want to avoid disportion
		// Do short side first, then figure out other dimention
		if ($origW > $origH) {
			// Horizontal orientation
			// Determine ideal scale
			$scale = floor($max_height / $origH);
			$new_height = $max_height;
			$new_width = $max_width;
			
			$optW = floor($origW*$scale);
			
			// Now we need to first crop image to the right proportions before scaling
			if ($max_width == $max_height) {
				$cropW = $origH;
				$cropH = $origH;							
				$origW = $cropW;
				$origH = $cropH;
			} elseif ($max_width < $max_height) {
				$ratio = $max_width/$max_height;
				$cropW = ($origW*$ratio);
				$cropH = $origH;
				$origW = $cropW;
				$origH = $cropH;
			} elseif ($max_width > $max_height) {
				$ratio = $max_height/$max_width;
				$cropW = $origW;
				$cropH = ($origH*$ratio);
				$origW = $cropW;
				$origH = $cropH;
			}		
			$im_out = imagecreatetruecolor($cropW, $cropH);
			imagecopy($im_out, $im_in, 0, 0, 0, 0, $cropW, $cropH);
			if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
				imagejpeg($im_out, $out_file, 100);
				$im_in = imagecreatefromjpeg($out_file);
			} elseif ($mime == "image/gif") {
				imagegif($im_out, $out_file, 100);
				$im_in = imagecreatefromgif($out_file);
			} elseif ($mime == "image/png") {
				imagepng($im_out, $out_file, 100);
				$im_in = imagecreatefrompng($orig_file);
			}						
				
		} elseif ($origW < $origH) {
			// Vertical orientation
			// Determine ideal scale
			$scale = floor($max_width / $origW);
			$new_width = $max_width;
			$new_height = $max_height;
			
			$optH = floor($origH*$scale);
			
			// Now we need to first crop image to the right proportions before scaling
			if ($max_width == $max_height) {
				$cropW = $origW;
				$cropH = $origW;							
				$origW = $cropW;
				$origH = $cropH;			
			} elseif ($max_width < $max_height) {
				$ratio = $max_width/$max_height;
				$cropW = ($origW*$ratio);
				$cropH = $origH;
				$origW = $cropW;
				$origH = $cropH;
			} elseif ($max_width > $max_height) {
				$ratio = $max_height/$max_width;
				$cropW = $origW;
				$cropH = ($origH*$ratio);
				$origW = $cropW;
				$origH = $cropH;
			}			
			$im_out = imagecreatetruecolor($cropW, $cropH);
			imagecopy($im_out, $im_in, 0, 0, 0, 0, $cropW, $cropH);
			if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
				imagejpeg($im_out, $out_file, 100);
				$im_in = imagecreatefromjpeg($out_file);
			} elseif ($mime == "image/gif") {
				imagegif($im_out, $out_file, 100);
				$im_in = imagecreatefromgif($out_file);
			} elseif ($mime == "image/png") {
				imagepng($im_out, $out_file, 100);
				$im_in = imagecreatefrompng($out_file);
			}			
		} elseif ($origW == $origH) {
			// Square - easy
			$new_width = $max_width;
			$new_height = $max_height;
		}
	} elseif (!empty($max_width) && empty($max_height)) {	
		$scale = ($max_width / $origW);
		$new_width = $max_width;
		$new_height = floor($origH * $scale);
	} elseif (!empty($max_height) && empty($max_width)) {
		$scale = ($max_height / $origH);
		$new_height = $max_height;
		$new_width = floor($origW * $scale);
	}
		
	$im_out = imagecreatetruecolor($new_width, $new_height);
	imagecopyresized($im_out, $im_in, 0, 0, 0, 0, $new_width, $new_height, $origW, $origH);
	if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
		imagejpeg($im_out, $out_file, 100);
	} elseif ($mime == "image/gif") {
		imagegif($im_out, $out_file, 100);
	} elseif ($mime == "image/png") {
		imagepng($im_out, $out_file, 100);
	}
	
	// Draw border
	if (!empty($border)) {
		if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
			$im_in =  imagecreatefromjpeg($out_file);
		} elseif ($mime == "image/gif") {
			$im_in =  imagecreatefromgif($out_file);
		} elseif ($mime == "image/png") {
			$im_in =  imagecreatefrompng($out_file);
		}
		$color = ImageColorAllocate($im_in,0,0,0);
		ImageLine($im_in,0,0,($max_width-1),0,$color); // Top
		ImageLine($im_in,($max_width-1),1,($max_width-1),($max_height-1),$color); // Right
		ImageLine($im_in,($max_width-1),($max_height-1),1,($max_height-1),$color); // Bottom
		ImageLine($im_in,0,($max_height-1),0,0,$color); // Left
		if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
			imagejpeg($im_in, $out_file, 100);
		} elseif ($mime == "image/gif") {
			imagegif($im_in, $out_file, 100);
		} elseif ($mime == "image/png") {
			imagepng($im_in, $out_file, 100);
		}
	}
	
	imagedestroy($im_out);
	imagedestroy($im_in);	
}

function replace_bad_chars($string) {
	global $new_string;
	$string = stripslashes($string);
	$new_string = $string;
	$badArray = array(Chr(47),Chr(34),Chr(35),Chr(39),Chr(32),Chr(92));
	$goodArray = array('','','','','_','');
	$elements = count($badArray);
	for($a=0;$a<=($elements-1);$a++) {
		$pat = $badArray[$a];
		$repl = $goodArray[$a];
		$new_string = (ereg_replace($pat, $repl, $new_string));
	}	
	return $new_string;
}

function daysBetweenDates($dateStart,$dateEnd) {
	global $days;
	$dateStartArray = explode("-",$dateStart);
	$dateEndArray = explode("-",$dateEnd);
	
	$startYear = $dateStartArray[0];
	$startMonth = $dateStartArray[1];
	$startDay = $dateStartArray[2];
	
	$endYear = $dateEndArray[0];
	$endMonth = $dateEndArray[1];
	$endDay = $dateEndArray[2];
	
	//first convert to unix timestamp
	$init_date = mktime(12,0,0,$startMonth,$startDay,$startYear);
	$dst_date = mktime(12,0,0,$endMonth,$endDay,$endYear);

	$offset = $dst_date-$init_date; //Depending on which offset type you want, switch order

	$days = floor($offset/60/60/24); 
	return $days;
}

function shortText($text,$words) {
	global $shortText;
	$text = strip_tags($text,'<a>');
	$textArray = explode(" ", $text);
	$newText = null;
	for($zz=0;$zz<=($words);$zz++) {
		$newText .= $textArray[$zz]." ";
	}
	$shortText = $newText."...";
	
	return $shortText;
}

function paginate($pages,$perPage,$urlString,$page,$pageNoOnly) {
	if (empty($page) || ($page == 0) ) { $page = 1;	}
	if (!empty($urlString)) { $urlString = "&".$urlString; }
	if ($pageNoOnly == 1) {
		echo "Page: ";
		for($p=1;$p<=$pages;$p++) {
			if ($p>1) { $start = ($p-1)*$perPage; }
			else { $start = 0; }
			if ($page == $p) { echo "<span class=orange><b>$p</b></span>\n"; }
			else { echo "<a href=\"".$_SERVER[PHP_SELF]."?page=$p&start=$start".$urlString."\"><b>$p</b></a>\n"; }
			if ($p < $pages) { echo " <font color=#c0c0c0>|</font> \n"; }
		}
	} else {
		echo "<div class=\"grayField\" style=\"text-align: right;\">Page: \n";
		for($p=1;$p<=$pages;$p++) {
			if ($p>1) { $start = ($p-1)*$perPage; }
			else { $start = 0; }
			if ($page == $p) { echo "<span class=orange><b>$p</b></span>\n"; }
			else { echo "<a href=\"".$_SERVER[PHP_SELF]."?page=$p&start=$start".$urlString."\"><b>$p</b></a>\n"; }
			if ($p < $pages) { echo " <font color=#c0c0c0>|</font> \n"; }
		}
		echo "</div>\n";
	}	
}

function microtime_float() {
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}

// Hover grabs some text from the database based on ID and displays
// content in mouseover popup using overLib javaScript library.
function hoverHelp($type='',$helpID) {
	global $linkHelp, $dbname, $db, $db_selected;
	
	// Get content from ss_help
	$sql = "SELECT * from ss_help WHERE HID = '$helpID'";
	$result = mysql_db_query($dbname,$sql);
	$rowHelp = mysql_fetch_assoc($result);
	
	$helpTitle = stripslashes($rowHelp[BriefDesc]);
	$helpText  = stripslashes($rowHelp[HelpText]);
	
	$helpText = "<b>$helpTitle</b><br>$helpText";
	
	$linkHelp = null;
	$linkHelp .= "<img src=\"images/help.png\" border=\"0\" style=\"cursor: help;\" onmouseover=\"return overlib('$helpText', STICKY, CENTER, MOUSEOFF, WRAP, CELLPAD, 5);\" onmouseout=\"return nd();\">";
	return $linkHelp;
}
function hoverProfile($uID) {
	global $linkProfile, $dbname, $db, $db_selected;
	$monthArray = array('0','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec');
	
	// Get user profile settings : we've already determined if profile is visible
	// before getting to this function. NO WE HAVEN'T! CHECK IT NOW!
	$sql = "SELECT ShowProfile from ss_userSettings WHERE UID = '$uID'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);	
	
	$sql = "SELECT * from ss_users WHERE UserID = '$uID'";
	$result = mysql_db_query($dbname,$sql);
	$rowProfile = mysql_fetch_assoc($result);
	
	if ($row[ShowProfile] == 1) {
		
		$userName   = $rowProfile[FirstName]." ".$rowProfile[LastName];
		$userImage  = $rowProfile[PhotoFile];
		if (!empty($rowProfile[PhotoFile])) {
			$userImage  = "users/".$rowProfile[FileDir]."/thumb_".$rowProfile[PhotoFile];
		} else {
			$userImage  = "images/user_no_photo.gif";
		}		
		$userHandle  = $rowProfile[Handle];
		$userLoc     = $rowProfile[Location];
		$userCountry = $rowProfile[Country]; 
		$userURL     = $rowProfile[URL];
		if (!empty($userHandle)) { $userLinkName = $userHandle; }
		else { $userLinkName = $userName; }
		
		$userIMICQ     = $rowProfile[IMICQ];
		$userIMMSN     = $rowProfile[IMMSN];
		$userIMAIM     = $rowProfile[IMAIM];
		$userIMYahoo   = $rowProfile[IMYahoo];
		
		$userBMonth    = $rowProfile[BirthMonth];
		$userBDay      = $rowProfile[BirthDay];
		
		$linkProfile = "<table border=0><tr><td valign=top><img src=$userImage title=$userName></td>";
		$linkProfile .= "<td valign=top><b>$userName</b><br>";
		if (!empty($userHandle)) { $linkProfile .= "$userHandle<br>"; }
		if (!empty($userLoc)) { $linkProfile .= "$userLoc<br>"; }
		if (!empty($userCountry)) { $linkProfile .= "$userCountry<br>"; }
		
		$linkProfile .= "</td></tr></table>";
		
		if (!empty($userURL)) { $linkProfile .= "<a href=$userURL target=_blank>$userURL</a><br>"; }
		if (!empty($userIMICQ)) { $linkProfile .= "ICQ Number: $userIMICQ<br>"; }
		if (!empty($userIMMSN)) { $linkProfile .= "MSN Handle: $userIMMSN<br>"; }
		if (!empty($userIMAIM)) { $linkProfile .= "AIM Screen Name: $userIMAIM<br>"; }
		if (!empty($userIMYahoo)) { $linkProfile .= "Yahoo! Handle: $userIMYahoo<br>"; }
		if (!empty($userBMonth) && !empty($userBDay)) { $linkProfile .= "Birthday: ".$monthArray[$userBMonth]." $userBDay<br>"; }
		
		$linkProfile .= "<br><div align=right><a href=myShop_userProfile.php?uID=$uID><b>View full profile for $userName</b></a> <font color=red><b>&raquo;</b></font></div>";
		
		$linkProfile = "<a href=\"#\" onmouseover=\"return overlib('$linkProfile', STICKY, CENTER, MOUSEOFF, WRAP, CELLPAD, 5);\" onmouseout=\"return nd();\">\n";
		$linkProfile .= "$userLinkName</a>";
	} else {
		$linkProfile = " &nbsp;".$rowProfile[FirstName]." ".$rowProfile[LastName];
	}
	return $linkProfile;
}
function buildBreadcrumb() {
	global $dbname, $db, $db_selected;
}

// resourceStats displays the Comments,Downloads,Views icons
// in file listResources.php
function resourceStats($rID,$rLink) {
	global $statString, $dbname, $db, $db_selected;
	// Get resource stats
	$sql = "SELECT Views,Downloads from ss_resource WHERE ID = '$rID'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	$views = $row[Views];
	$downloads = $row[Downloads];
	
	$sql = "SELECT ID from ss_resourcePost WHERE RID = '$rID'";
	$result = mysql_db_query($dbname,$sql);
	$comments = mysql_num_rows($result);
	
	$statString  = "<a href=\"http://www.sonixshop.com/".$rLink."\" title=\"$comments Comments\"><img src=\"images/icon_word_baloon_small.gif\" border=\"0\"></a> <span class=smallGray>$comments</span>&nbsp;\n";
	$statString .= "<a href=\"http://www.sonixshop.com/".$rLink."\" title=\"$downloads Downloads\"><img src=\"images/icon_small_downloads.gif\" border=\"0\"></a> <span class=smallGray>$downloads</span>&nbsp;\n";
	$statString .= "<a href=\"http://www.sonixshop.com/".$rLink."\" title=\"$views Views\"><img src=\"images/icon_small_view.png\" border=\"0\"></a> <span class=smallGray>$views</span>&nbsp;\n";
	
	return $statString;
}

// adCodeGrabber gets random ad code for a specified ad zone
// ZONES:
//	1. Header
//	2. Right Column
//	3. Bottom of page
//	4. Below Main Menu on Left
function adCodeGrabber($zone) {
	global $codeString, $dbname, $db, $db_selected;
	
	// Get all adCodeID's for this zone
	$sql = "SELECT CodeID from ss_adCode WHERE AdZone = '$zone' AND Active = '1'";
	$result = mysql_db_query($dbname,$sql);
	$i=0;
	while ($value = mysql_fetch_assoc($result)) {
		$codeIDArray[$i] = $value[CodeID];
		$i++;
	}
	$codes = count($codeIDArray);
	
	// Get random codeID
	srand((double)microtime()*1000000);
	$randomCodeID = rand(1,($codes));
	$randomCodeID = $codeIDArray[$randomCodeID-1];
	
	// Get ad code
	$sql = "SELECT AdCode from ss_adCode WHERE CodeID = '$randomCodeID'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	$codeString = $row[AdCode];
	
	return $codeString;
}

// Mail Jeff sends Jeff an email at critical points: 
// registration, contact, feature request, link to us, etc.
function mailAdmin($fromWhere,$name,$email,$title=null,$url=null) {
	global $masterMail;
	if (empty($name)) { $name = "Joe User"; }
	if (empty($email)) { $email = "info@tcnTransition.org"; }
	
	if ($fromWhere == "registration") {
		$subject     = "soniXshop Registration";
		$fromName    = $name;
		$fromAddress = $email;
		$to          = $masterMail;
		$message     = "$name has become a soniXshop member.";		
		mailNew($fromName, $fromAddress, $to, $subject, $message);
	} elseif ($fromWhere == "contact") {
		$subject     = "TCN Contact Form";
		$fromName    = $name;
		$fromAddress = $email;
		$to          = $masterMail;
		$message     = "$name has contacted the Transition Community Network by email. To view this message, please follow this link and log in to your admin account:
http://www.tcnTransition.org/admin";		
		mailNew($fromName, $fromAddress, $to, $subject, $message);	
	} elseif ($fromWhere == "feature") {
		$subject     = "soniXshop Feature Request";
		$fromName    = $name;
		$fromAddress = $email;
		$to          = $masterMail;
		$message     = "$name has submitted a soniXshop Feature Request.";		
		mailNew($fromName, $fromAddress, $to, $subject, $message);
	} elseif ($fromWhere == "link") {
		$subject     = "soniXshop Link to Us";
		$fromName    = $name;
		$fromAddress = $email;
		$to          = $masterMail;
		$message     = "$name has downloaded a soniXshop Link Banner.";		
		mailNew($fromName, $fromAddress, $to, $subject, $message);
	} elseif ($fromWhere == "newResource") {
		$subject     = "New Resource Added";
		$fromName    = $name;
		$fromAddress = $email;
		$to          = $masterMail;
		$message     = "$name has posted a new resource.\n\n";
		$message    .= "$title\n$url\n\n";
		$message    .= "This resource has not been approved and activated so it will not appear on the website.\n";
		$message    .= "Log into your admin account to approve this resource.\n";
		$message    .= "http://www.tcnTransition.org/admin";		
		mailNew($fromName, $fromAddress, $to, $subject, $message);		
	} elseif ($fromWhere == "emailFriend") {
		$subject     = "soniXshop Email Resource to Friend";
		$fromName    = $name;
		$fromAddress = $email;
		$to          = $masterMail;
		$message     = "$name has emailed a resource to a friend.";		
		mailNew($fromName, $fromAddress, $to, $subject, $message);
	}
}

function deleteProject($pID) {
	global $dbname, $db, $db_selected;

	// This function deletes everything associated with a project
	
	// 1.  Delete main project record
	$sql = "DELETE from ss_project WHERE PID = '$pID'";
	$result = mysql_db_query($dbname,$sql);
	
	// 2.  Delete project calculation records
	$sql = "DELETE from ss_projectCalc WHERE PID = '$pID'";
	$result = mysql_db_query($dbname,$sql);
	
	// 3. Delete project part records
	$sql = "DELETE from ss_projectParts WHERE PID = '$pID'";
	$result = mysql_db_query($dbname,$sql);
	
	// 4. Delete project parts name record
	$sql = "DELETE from ss_projectPartsName WHERE PID = '$pID'";
	$result = mysql_db_query($dbname,$sql);
	
	// 5. Delete project resource entries
	$sql = "DELETE from ss_projectResource WHERE PID = '$pID'";
	$result = mysql_db_query($dbname,$sql);	
}

function deletePartsList($plID) {
	global $dbname, $db, $db_selected;

	// This function deletes everything associated with a parts list	
	// 1. Delete project part records
	$sql = "DELETE from ss_projectParts WHERE LID = '$plID'";
	$result = mysql_db_query($dbname,$sql);
	
	// 2. Delete project parts name record
	$sql = "DELETE from ss_projectPartsName WHERE ID = '$plID'";
	$result = mysql_db_query($dbname,$sql);
}

function buildBreadcrumbs($path) {
	global $subSubCatName, $breadCrumbs, $dbname, $db, $db_selected;
	// $path is in the form of /mainCat/subCat/subSubCat
	
	$pathArray = explode('/',$path);
	$mainCat   = $pathArray[1];
	$subCat    = $pathArray[2];
	$subSubCat = $pathArray[3];
	
	$sql = "SELECT * from transLevels WHERE Path = '/$mainCat'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	$mainCatName = stripslashes($row[LevelName]);
	
	$sql = "SELECT * from transLevels WHERE Path = '/$mainCat/$subCat'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	$subCatName = stripslashes($row[LevelName]);
	
	$sql = "SELECT * from transLevels WHERE Path = '/$mainCat/$subCat/$subSubCat'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	$subSubCatName = stripslashes($row[LevelName]);
	
	$breadCrumbs = "<a href=\"$siteURL/$mainCat\" class=\"orangeLink\">$mainCatName</a> :\n";
	$breadCrumbs .= "<a href=\"$siteURL/$mainCat/$subCat\" class=\"orangeLink\">$subCatName</a>\n";
	//$breadCrumbs .= "<a href=\"$siteURL/$mainCat/$subCatName/$subSubCat\" class=\"orangeLink\">$subSubCatName</a>\n";
	
	return $subSubCatName;
	return $breadCrumbs;
}

function badLink($linkID=null) {
	global $masterMail, $webmasterMail, $dbname, $db, $db_selected;
	if (!empty($linkID)) {
		$sql = "UPDATE transLinks SET 
					ErrorCode = 'userbl',
					ErrorDate = '".date('Y-m-d')."'
					WHERE
					LinkID = '$linkID'";
		$result = mysql_db_query($dbname,$sql);
		
		// Get info for email notification
		$sql = "SELECT Path,Title,Link from transLinks WHERE LinkID = '$linkID'";
		$result = mysql_db_query($dbname,$sql);
		$row = mysql_fetch_assoc($result);
		
		$path  = $row[Path];
		$title = stripslashes($row[Title]);			
		$url   = $row[Link];
		
		// Send notification
		$fromName    = 'TCN Website';
		$subject     = 'Broken link notification';
		$fromAddress = $masterMail;
		$to          = $webmasterMail;
		//$to = 'jdenton@quik.com';
		$message     = '
A broken link notification has been sent by a TCN user. See details below...
----------------------------------------------------------------------------
Title:  '.$title.'
URL:    '.$url.'
Where to find:  http://www.tcntransition.org'.$path.'
		';
		mailNew($fromName, $fromAddress, $to, $subject, $message);
	}	
	return $linkID;
}

// convertDateTime takes a MySQL DateTime field in form of// YYYY-MM-DD HH:MM:SS and converts it to Jan 1, 2007 7:05am// Remember: 00:00:00 = 12:00am, 23:59:59 = 11:59:59pmfunction convertDateTime($dateTime) {	global $returnArray,$convertedDate;		$dateTimeArray = explode(' ',$dateTime);	$date = $dateTimeArray[0];	$time = $dateTimeArray[1];	$timeArray = explode(':',$time);	$hour = $timeArray[0];	$min  = $timeArray[1];	$sec  = $timeArray[2];		// Assumption: if 00:00:00, let's assume no time was entered	if ( ($hour=='00') && ($min=='00') && ($sec=='00') ) { $newTime = ''; }	else {			if ($hour>11) { $ampm = 'pm'; }			else { $ampm = 'am'; }						if (substr($hour,0,1)==0) { $hour = substr($hour,1,1); }						if ($hour>12) { $hour = $hour-12; }								$newTime = $hour.':'.$min.$ampm;	}			if ($date != '0000-00-00') {		$newDate = mysql_to_date2($date);	} else {		$newDate = '';	}		$returnArray = array($newDate,$newTime);	return $returnArray;		}
function getCategories($display=null,$siteArea,$selected=null) {
	global $catString, $dbname, $db, $db_selected, $pre;
	$catString = '';	// Get news and announcements	$sql = "SELECT * from casa_categories WHERE CatType = '$siteArea' ORDER BY CatOrder,CatName";	$result = mysql_db_query($dbname,$sql);
	while ($value = mysql_fetch_assoc($result)) {		$catID   = $value[CID];		$catName = stripslashes($value[CatName]);
		if ($display == 'select') {			$catString .= '<option value="'.$catID.'"';			if ($selected == $catID) { 				$catString .= ' selected ';			}				$catString .= '>'.$catName.'</option>';		}
	}	return $catString;}

function getPrograms($display=null,$selected=null) {
	global $catString, $dbname, $db, $db_selected, $pre;

	$progString = '';
	$sql = "SELECT * from casa_programs ORDER BY ProgramName";
	$result = mysql_db_query($dbname,$sql);
	while ($value = mysql_fetch_assoc($result)) {
		$pID   = $value[PID];
		$pName = stripslashes($value[ProgramName]);

		if ($display == 'select') {
			$progString .= '<option value="'.$pID.'"';
			if ($selected == $pID) { 
				$progString .= ' selected ';
			}	
			$progString .= '>'.$pName.'</option>';
		}	
	}
	return $progString;
}

function sendMailAccountInfo($email,$uID=null,$newAccount=null) {
	global $arrayUploadNotify, $dbname, $db, $db_selected;

	// Get user information
	$sql = "SELECT * from casa_users WHERE UID = '$uID'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	$userid = $row[Userid];
	$password = $row[Password];
	$fullName = $row[NameFirst].' '.$row[NameLast];
	
    // Send message
	$to          = $email;
	$fromName    = 'CASA3G';
	$fromAddress = 'noreply@casa3g.org';
	$subject     = 'Your CASA3G Account Information';
	$message     = $fullName.','.Chr(10);
	$message    .= 'Your CASA3G account login is:'.Chr(10).Chr(10);
	$message    .= 'User Name: '.$userid.Chr(10);
	$message    .= 'Password:  '.$password.Chr(10).Chr(10);
	$message    .= 'If you have any questions, please contact the webmaster at '.WEBMASTER_MAIL; 
	
	// Send mail to user
	mailNew($fromName, $fromAddress, $to, $subject, $message);
	
	if ($newAccount == 1) {
		// Also send email to administrators
		$subject = 'CASA3G: New User Account';
		$message .= Chr(10).'--------------------------------------------------------'.Chr(10);
		$message .= 'This message was sent to notify you of a new user account.';
			
		for($a=0;$a<=(count($arrayUploadNotify)-1);$a++) {
			$to = $arrayUploadNotify[$a];
			mailNew($fromName, $fromAddress, $to, $subject, $message);
		}	
	}
}

function sendMailRegistrationInfo($email,$uID=null,$eID=null) {
	global $eArray, $dbname, $db, $db_selected;
	
	$userArray = getUserDetails($uID);
	$eventArray = getEventDetails($eID);	
	
	$fullName = $userArray[1].' '.$userArray[2];
	
	$eventTitle    = DBToField($eventArray[4]);
	$eventLocation = DBToEmail($eventArray[5]);  
	$eventDesc     = DBToEmail($eventArray[6]);
	$eventURL      = $eventArray[7];
	$eventDateStartArray = convertDateTime($eventArray[9]);
	$eventDateEndArray   = convertDateTime($eventArray[10]);
	$eventTimes    = $eventArray[11];
		
    // Send message
	$to          = $email;
	$fromName    = 'CASA3G';
	$fromAddress = 'noreply@casa3g.org';
	$subject     = 'CASA3G.ORG Event Registration';
	$message     = $fullName.','.Chr(10);
	$message    .= 'Thank you for registering. The event information is listed below.'.Chr(10).Chr(10);
	
	$message    .= '**** '.$eventTitle.' *****'.Chr(10).Chr(10);
	if (!empty($eventDesc)) {
		$message .= $eventDesc.Chr(10).Chr(10);
	}
	if (!empty($eventLocation)) {
		$message .= 'Location: '.$eventLocation.Chr(10);
	}
	if (!empty($eventDateStartArray[0])) {
		$message .= 'Date(s):  '.$eventDateStartArray[0].' '.$eventDateStartArray[1];
	}
	if (!empty($eventDateEndArray[0])) {
		$message .= ' to '.$eventDateEndArray[0].' '.$eventDateEndArray[1].Chr(10);
	}
	if (!empty($eventTimes)) {
		$message .= 'Time:     '.$eventTimes;
	}
	$message    .= Chr(10).'If you have any questions, please contact '.INFO_MAIL; 
	
	// Send mail to user
	mailNew($fromName, $fromAddress, $to, $subject, $message);
	
	// Also send email to administrators
	$subject = 'CASA3G: Event Registration';
	$message .= Chr(10).'--------------------------------------------------------'.Chr(10);
	$message .= 'This message was sent to notify you of a new event registration.';
			
	for($a=0;$a<=(count($arrayUploadNotify)-1);$a++) {
		$to = $arrayUploadNotify[$a];
		//mailNew($fromName, $fromAddress, $to, $subject, $message);
	}	
}


?>